//
//  SystemVoiceItemView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/18.
//

import SwiftUI
import Kingfisher
import SwiftEntryKit

//日记 item
struct DiaryItemView: View {
    @EnvironmentObject var pathManager: PathManager
    @StateObject var viewModel : DiaryItemViewModel
    @State private var showFullScreen = false //预览图片
    @State private var selectedIndex = 0
    @State private var showDelDialog = false //删除日记
    @State private var showDelAiDialog = false //删除回应
    @State private var showHistoryComment = false //历史评论
    @State private var refresh = false
    @State private var showComment = false //显示评论，常用语折叠评论点击显示

    @State private var date : Date = Date()
    
    init(bean: DiaryBean) {
        _viewModel = StateObject(wrappedValue: DiaryItemViewModel(bean: bean))
    }
    
    var body: some View {
        HStack(alignment: .top, spacing: 0) {
            VStack(spacing: 0){
                Image(MoodExt.getMoodRes(viewModel.bean.mood))
                    .resizable()
                    .frame(width: 30, height: 30)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showMoodPopup()
                    }
                VerticalDashedLine()
                    .stroke(style: StrokeStyle(lineWidth: 1, dash: [5, 5])) // 设置线宽和虚线模式
                    .frame(width: 1) // 设置竖线的宽度和高度
                    .foregroundColor(.colorLine2) // 设置线条颜色
            }
            //右边内容
            VStack(alignment:.leading,spacing: 0) {
                Text(DiaryDateExt.getTimeStr(AppStorageManager.shared.dateMode, viewModel.bean.time))
                    .font(.system(size: 14,weight: .semibold))
                    .foregroundStyle(.bgNormalText2)
                    .padding(.top, 7)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showTimePopup()
                    }
                Text(viewModel.bean.content ?? "")
                    .font(.system(size: 15))
                    .foregroundStyle(.bgTextTitle)
                    .kerning(1)//字间距稍微扩大一点
                    .padding(.top, 3)
                    .fixedSize(horizontal: false, vertical: true) // 允许垂直扩展
                //声音
                if !(viewModel.bean.sound?.url ?? "").isEmpty {
                    VoiceView(bean: viewModel.bean.sound).padding(.top, 5)
                }
                //图片列表
                if viewModel.bean.listDiaryPicture?.isEmpty == false {
                    pictureView
                        .padding(.top, 15)
                        .padding(.bottom, 10)
                }
                //标签
                if !(viewModel.bean.tagName ?? "").isEmpty {
                    Text(viewModel.bean.tagName ?? "")
                        .font(.system(size: 11))
                        .foregroundStyle(themeManager.themeColor)
                        .padding(EdgeInsets(top: 2, leading: 5, bottom: 2, trailing: 5))
                        .background(themeManager.themeColor.opacity(0.2))
                        .cornerRadius(4)
                        .padding(.top, 5)
                }
                //地址
                if !(viewModel.bean.location?.name ?? "").isEmpty {
                    Text(viewModel.bean.location?.name ?? "")
                        .font(.system(size: 10))
                        .foregroundStyle(.bgNormalText4)
                        .padding(.top, 5)
                }
                //评论
                if viewModel.commentStatus > 0 && (viewModel.bean.temOther ?? []).isEmpty == false {
                    commentView
                }
                // 设置空白区域的高度，提高美观，为了就是左边的虚线要比右边长
                Color.clear
                    .frame(height: 10)
            }.frame(maxWidth: .infinity, alignment: .leading)
        }.frame(maxHeight: .infinity, alignment: .leading)
            .padding(.leading, 5)
            .padding(.trailing,10)
            .contentShape(Rectangle())
            .onTapGesture {
                jumpDiary()
            }
            .contextMenu {
                contextMenuView
            }.alert("温馨提示",isPresented:$showDelDialog) {
                Button("取消",role: .cancel){}
                Button("确定删除",role: .destructive) {
                    viewModel.delete(bean: viewModel.bean) {
                        NotificationCenter.default.post(name: .delDiary, object: viewModel.bean) //发送事件
                    }
                }
            } message: {
                Text("您确定是否要删除该条数据，删除后将无法恢复")
            }
            .alert("温馨提示",isPresented:$showDelAiDialog) {
                Button("取消",role: .cancel){}
                Button("确定删除",role: .destructive) {
                    viewModel.delAIReply(diaryBean: $viewModel.bean, aiRoleId : getFirstAiRoleId())
                }
            } message: {
                Text("是否确定删除该回应")
            }
            .sheet(isPresented: $showHistoryComment) {
                HistoryCommentDialogView(bean: $viewModel.bean,aiRoleId: getFirstAiRoleId()) {
                    showHistoryComment = false
                }.presentationDetents([.fraction(0.9), .large])
                
            }
    }
    func getFirstAiRoleId() -> String {
        var aiRoleId = ""
        if  viewModel.bean.roleType == IRoleType.BOT.rawValue {
            aiRoleId = viewModel.bean.roleId ?? ""
        } else {
            aiRoleId = viewModel.bean.aiRule?.getFirstRoleId() ?? ""
        }
        return aiRoleId
    }
    //跳转到日记
    func jumpDiary() {
        pathManager.jump(type: JumpType.DIARY, data: viewModel.bean)
    }
    
}

extension DiaryItemView {
    class MediaBean : Identifiable {
        let id = UUID()
        var media : MediaItem? = nil
        var picture : CloudPictureBean? = nil
    }
    
    struct DiaryPictureItemView : View {
        var item: MediaBean
        var body: some View {
            ZStack(alignment: .topTrailing) {
                if let imedia = item.media {
                    PictureItemView(item: imedia, itemWidth: 80, itemHeight: 80, cornerRadius: 17)
                }
                if (item.picture?.describe ?? "")?.isEmpty == false {
                    ZStack {
                        Image(.homeIconEye)
                            .resizable()
                            .frame(width: 10, height: 10)
                    }.padding(5)
                        .background {
                            themeManager.themeColor
                                .opacity(0.7)
                                .clipShape(UnevenRoundedRectangle(
                                    topLeadingRadius: 0,    // 左上角
                                    bottomLeadingRadius: 17, // 左下角
                                    bottomTrailingRadius: 0,// 右下角
                                    topTrailingRadius: 17    // 右上角
                                ))
                        }
                }
            }
        }
    }
    
    //图片列表
    var pictureView: some View {
        ScrollView(.horizontal,showsIndicators: false) {
            VStack(alignment: .leading, spacing: 0) {
                //横向布局
                HStack(spacing:10) {
                    ForEach(Array(viewModel.mediaItems.enumerated()), id: \.element.id) { index, item in
                        DiaryPictureItemView(item: item)
                            .onTapGesture {
                                selectedIndex = index
                                showFullScreen.toggle()
                            }
                    }
                }
            }
        }.fullScreenCover(isPresented: $showFullScreen) {
            FullScreenMediaView(mediaItems: viewModel.mediaItems.map {$0.media ?? MediaItem(type: MediaType.localImagePath(""))}, currentIndex: $selectedIndex)
        }.onAppear{
            if viewModel.mediaItems.isEmpty {
                viewModel.getPicture(bean: viewModel.bean)
            }
        }
        
    }
    
    func showTimePopup() {
        date = Date(timeIntervalSince1970: TimeInterval(viewModel.bean.time) / 1000)
        SwiftEntryKitWrapper.showBottomPopup { dissmis in
            PickDateView(title: "    修改时间", selectedDate: $date) {
                viewModel.bean.time = Int64(date.timeIntervalSince1970 * 1000)
                viewModel.save(diaryBean: viewModel.bean)
                dissmis()
            }
        }
    }
    
    func showMoodPopup() {
        SwiftEntryKitWrapper.showBottomPopup{ dismiss in
            MoodDialogView() { mood in
                viewModel.bean.mood = mood
                viewModel.save(diaryBean: viewModel.bean)
                dismiss()
            }
        }
    }
}

extension DiaryItemView {
    var contextMenuView: some View {
        Group {
            Button("查看") {
                jumpDiary()
            }
            Button("修改") {
                pathManager.jump(type: JumpType.ADD_DIARY, data: viewModel.bean)
                
            }
            Button("修改时间") {
                showTimePopup()
            }
            Button("删除", role: .destructive) {
                showDelDialog.toggle()
            }
            Menu {
                Button("装扮气泡") {
                    pathManager.jump(type: JumpType.BUBBLE_DIARY,data: viewModel.bean)
                }
                Button(showComment ? "关闭评论" : "显示评论") {
                    showComment = !showComment
                }
                Button("评论") {
                    NotificationCenter.default.post(name: .showComment, object: (viewModel.bean, getFirstAiRoleId()))
                }
            } label: {
                Button("评论相关"){} // 可以添加图标表示层级
            }
            //                Button("评论") {
            //                    showComment.toggle()
            //                }
            if viewModel.bean.roleType == IRoleType.USER.rawValue {
                // 将 Button 改为嵌套的 Menu
                Menu {
                    Button("重新回应") {
                        ActiveAiExt.doAiReply(viewModel.bean, getFirstAiRoleId())
                    }
                    Button("删除回应", role: .destructive) {
                        showDelAiDialog.toggle()
                    }
                    Button("历史回应") {
                        showHistoryComment.toggle()
                    }
                } label: {
                    Button("回应相关操作"){} // 可以添加图标表示层级
                }
            }
        }
    }
}

//评论
extension DiaryItemView {
    //获取显示模式
    func getShowComment() {
        switch AppStorageManager.shared.foldMode {
        case .TYPE_DAY:
            if TimeUtils.isToday(getSecond(time: viewModel.bean.time)) {
                showComment = true
            } else {
                showComment = false
            }
        case .TYPE_MONTH:
            if TimeUtils.isSameMonth(getSecond(time: viewModel.bean.time), getNetTimeLocal()) {
                showComment = true
            } else {
                showComment = false
            }
        case .TYPE_YEAR:
            if TimeUtils.isSameYear(getSecond(time: viewModel.bean.time), getNetTimeLocal()) {
                showComment = true
            } else {
                showComment = false
            }
        case .TYPE_ALL:
            showComment = true
        case .TYPE_CLOSE:
            //全部折叠
            showComment = false
        }
    }
    var commentView: some View {
        Group {
            if showComment {
                commentStyleView
            } else {
                commentFoldStyleView
            }
        }.onAppear{
            getShowComment()
        }
        
    }
    //评论样式
    var commentStyleView: some View {
        DiaryCommentView(diaryBean: $viewModel.bean, commentStatus: $viewModel.commentStatus,viewModel: viewModel)
            .padding(.trailing, 20)
            .padding(.leading, -12)
    }
    
    //评论折叠样式
    var commentFoldStyleView: some View {
        Group {
            switch AppStorageManager.shared.foldStyle {
            case .TYPE_AVATAR:
                //折叠头像
                HStack(spacing: 0) {
                    ForEach(Array((viewModel.bean.temOther?.filter {  viewModel.bean.roleType == IRoleType.BOT.rawValue ? !$0.bot : $0.bot } ?? []).enumerated()), id: \.element.avatar) { index, item in
                        AvatarImageView(url: item.avatar ?? "", size: 25)
                            .overlay(
                                RoundedRectangle(cornerRadius: 12.5) // 与头像圆角一致（25/2=12.5）
                                    .stroke(Color.white, lineWidth: 0.8) // 白框颜色+宽度
                            )
                            .padding(.leading, index == 0 ? 0 : -12)
                    }
                }
                //
            case .TYPE_TEXT:
                //折叠名称
                Text(
                    viewModel.bean.temOther?
                        .filter { viewModel.bean.roleType == IRoleType.BOT.rawValue ? !$0.bot : $0.bot } // 筛选 bot 为 true 的元素（你的过滤条件）
                        .compactMap { $0.name } // 提取 name，自动过滤 nil（转为 [String]）
                        .filter { !$0.isEmpty } // 可选：过滤空字符串（避免 "、" 连续）
                        .joined(separator: "、") ?? "" // 用「、」拼接，nil 兜底空字符串
                ).font(.system(size: 11))
                    .foregroundStyle(.bgNormalText4)
            case .TYPE_HIDE:
                //直接不展示
                Color.clear
            }
            
        }.padding(.top,3)
            .contentShape(Rectangle())
            .onTapGesture {
                showComment = true
            }
    }
}

//#Preview {
//    DiaryItemView(item:  DiaryBean(content: "我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试"))
//}

//定义预览提供者
struct DiaryItem_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for:  DiaryItemView(bean: DiaryBean(content: "我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试我在测试")))
    }
}
